package cn.fuxi2022.auth.controller;

import cn.fuxi2022.auth.service.UserLoginService;
import cn.fuxi2022.commons.redis.service.CaptchaService;
import cn.fuxi2022.core.exception.SmartGroupException;
import cn.fuxi2022.core.model.empty.auth.UserLogin;
import cn.fuxi2022.core.utils.JwtUtils;
import cn.fuxi2022.core.utils.PasswordUtils;
import cn.fuxi2022.core.utils.SmsUtils;
import cn.fuxi2022.model.resp.PageUtils;
import cn.fuxi2022.model.resp.R;
import cn.fuxi2022.model.vo.auth.UserLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 后台管理系统的登录 与 管理
 */
@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 登录方法，判断用户名和密码是否正确，正确下发token，否则提示错误
     *
     * @return token
     */
    @PostMapping("/login")
    public R login(@RequestBody @Validated UserLoginVo userLoginVo) {
        return R.ok("登录成功").data("token", userLoginService.login(userLoginVo.getPhone(), userLoginVo.getPassword()));
    }

    @GetMapping("/get")
    public R get(HttpServletRequest httpServletRequest) {
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        if (!StringUtils.hasText(id)) {
            return R.error("token非法");
        }
        UserLogin userLogin = userLoginService.getById(id);
        userLogin.setPassword(null);
        return R.ok().data(userLogin);
    }

    @GetMapping("/get/{id}")
    public R getById(@PathVariable("id") String id) {
        UserLogin userLogin = userLoginService.getById(id);
        userLogin.setPhone(null);
        userLogin.setPassword(null);
        userLogin.setIsDeleted(null);
        return R.ok().data(userLogin);
    }

    @GetMapping("/getAll")
    public R getAll() {
        List<UserLogin> list = userLoginService.list();
        list.forEach(userLogin -> {
            userLogin.setPassword(null);
            userLogin.setIsDeleted(null);
        });
        return R.ok().data(list);
    }

    @GetMapping("/get/phone/{id}")
    public String getPhoneById(@PathVariable("id") String id) {
        return userLoginService.getById(id).getPhone();
    }
    // ----------------------------------------------------------------------


    /**
     * 列表
     */
    @PostMapping("/list")
    public R list(@RequestBody Map<String, Object> params) {
        PageUtils page = userLoginService.queryPage(params);

        return R.ok().data(page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        UserLogin userLogin = userLoginService.getById(id);

        return R.ok().data("userLogin", userLogin);
    }

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private SmsUtils smsUtils;

    @GetMapping("/updateUser/captcha")
    public R updateUserSendCaptcha(HttpServletRequest httpServletRequest) {
        // 当前的管理员用户
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 获取当前用户的手机号
        String phone = getPhoneById(id);
        // 发送验证码
        String captcha;
        // 1.将验证码传入redis
        if (!(StringUtils.hasText(captcha = captchaService.saveCaptcha(phone)))) {
            throw new SmartGroupException("你已经获取过验证码了，稍后再试吧");
        }

        // 2.使用短信平台发送验证码短信
        if (!smsUtils.sendCaptcha(phone, captcha, "1")) {
            throw new SmartGroupException("验证码发送失败，请检查手机号");
        }
        return R.ok("发送验证码成功");
    }

    /**
     * 修改
     */
    @PutMapping("/update/{id}")
    public R update(@PathVariable("id") String id, HttpServletRequest httpServletRequest, @RequestBody Map<String, Object> params) {
        // 1.获取前端所参数
        Object phoneObj = params.get("phone");
        Object codeObj = params.get("code");
        Object passwordObj = params.get("password");

        // 2.合法校验
        if (ObjectUtils.isEmpty(phoneObj) || ObjectUtils.isEmpty(codeObj) || ObjectUtils.isEmpty(passwordObj)) {
            throw new SmartGroupException("修改管理员失败，传递的参数非法");
        }

        String phone = String.valueOf(phoneObj);
        String code = String.valueOf(codeObj);
        String password = String.valueOf(passwordObj);

        // 3.判断验证码是否合法
        if (!captchaService.checkCaptcha(code, getPhoneById(JwtUtils.getMemberIdByJwtToken(httpServletRequest)))) {
            throw new SmartGroupException("验证码错误，请重新输入");
        }

        // 4.获取用户
        UserLogin login = userLoginService.getById(id);
        if (ObjectUtils.isEmpty(login)) {
            throw new SmartGroupException("修改管理员失败，该ID对应的管理员不存在");
        }

        // 5.判断手机号是否已经注册了
        LambdaQueryWrapper<UserLogin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLogin::getPhone, phone);
        if (userLoginService.count(wrapper) > 0) {
            throw new SmartGroupException("当前手机号已经注册了，请重新输入未注册的手机号");
        }

        // 6.修改用户（注意，没有校验手机号）
        login.setPhone(phone);
        login.setPassword(PasswordUtils.encode(password));
        userLoginService.updateById(login);

        return R.ok("修改管理员成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    public R delete(@RequestBody String[] ids) {
        // 判断用户是否注册
        Arrays.asList(ids).forEach(s -> {
            UserLogin userLogin = userLoginService.getById(s);
            if (StringUtils.hasText(userLogin.getPhone())) {
                throw new SmartGroupException("不能删除已经注册成功的用户");
            }
        });

        // 删除用户
        userLoginService.removeByIds(Arrays.asList(ids));

        return R.ok("删除管理员成功");
    }
}
